/**
 *
 */
package com.androidnetframe;

import android.app.Application;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.util.Log;

import com.androidnetframe.cache.FileCacheFactory;
import com.androidnetframe.cache.NetScanner;
import com.androidnetframe.exception.BaseProcessCodeType;
import com.androidnetframe.exception.CodeTypeHandler;
import com.androidnetframe.httputil.EntryPageName;
import com.androidnetframe.httputil.NetConnectionChangeReceiver;
import com.androidnetframe.requestbean.GlobalRequestBean;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.util.Random;

/**
 * @author 何强
 *         2015-9-22
 *         创建这个对象的目的是包含：网络监测对象和文件缓存对象
 */
public class ConfigUtil {
    public static NetScanner netScanner;
    public static FileCacheFactory fileCacheFactory;
    public static Application context;
    public static CodeTypeHandler codeTypeHandler;
    public static String aesSecretKey;
    public static ConfigUtil configUtil;

    public ConfigUtil(Application context) {
        configUtil = this;
        this.context = context;
        //1.创建网络环境侦测对象
        netScanner = new NetScanner(context);
        //2.创建文件缓存对象
        fileCacheFactory = new FileCacheFactory(context);
        //注册断网监听广播,当网络发生改变时，会重置NetScanner的成员变量
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        context.registerReceiver(new NetConnectionChangeReceiver(), intentFilter);
        //注册异常捕获器
        instanceExceptionHandler();

        //获取服务器的基地址
        fetchBaseUrlFromServer();

    }

    public static int fetchState = -1;//正在获取的过程中

    public void fetchBaseUrlFromServer() {
        HttpUtils client = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("nns_tag", "android_phone");
        client.send(HttpRequest.HttpMethod.POST, EntryPageName.globalRequest, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> response) {
                fetchState = 1;//获取成功
                GlobalRequestBean globalRequestBean = new Gson().fromJson(response.result, GlobalRequestBean.class);
                Log.e("fetchBaseUrlFromServer",response.result);
                EntryPageName.globalRequestBean = globalRequestBean;

                if (firstRequest != null) {
                    firstRequest.run(true);
                }
                Intent intent = new Intent();
                intent.setAction("com.mmlc.meiqi.BaseRequestSuccess");
                context.sendBroadcast(intent);
            }

            @Override
            public void onFailure(HttpException e, String s) {
                fetchState = 2;//获取失败
                if (firstRequest != null) {
                    firstRequest.run(false);
                }
            }
        });
    }

    public FirstRequest firstRequest;

    public interface FirstRequest {
        void run(boolean isSuccess);
    }

    public void setFirstRequestListener(FirstRequest firstRequest) {
        this.firstRequest = firstRequest;
    }

    private void instanceExceptionHandler() {
        codeTypeHandler = new CodeTypeHandler(context);
        //添加一个用于处理奔溃性异常的类
        /*Thread.setDefaultUncaughtExceptionHandler(codeTypeHandler.getUncaughtExceptionHandler(context));*/
    }

    public static String initAESSecretkey() {
        StringBuilder tempString = new StringBuilder();
        for (int i = 0; i < 16; i++) {
            Random random = new Random();
            int nextInt = random.nextInt(10);
            tempString.append(String.valueOf(nextInt));
        }
        String secretKey = tempString.toString();
        aesSecretKey = secretKey;

        SharedPreferences settings;
        SharedPreferences.Editor localEditor;
        settings = context.getSharedPreferences("AesSecretKey_Folder", 0);
        localEditor = settings.edit();
        localEditor.putString("AesSecretKey", aesSecretKey);
        localEditor.commit();
        return secretKey;
    }

/*    public static AES getAESInstance(Context context) {
        SharedPreferences settings;
        settings = context.getSharedPreferences("AesSecretKey_Folder", 0);
        String secretKey = settings.getString("AesSecretKey", null);
        if (secretKey != null) {//如果本地没有AES的私钥，那么就用默认的私钥
            char[] tempChar = new char[secretKey.length()];
            for (int i = 0; i < secretKey.length(); i++) {
                tempChar[i] = secretKey.charAt(i);
            }
            AES.humanPassphrase = tempChar;
        }
        return new AES();
    }*/

    public static Class<? extends BaseProcessCodeType> processCodeTypeClass;

    public static void registerProcessCodeType(Class<? extends BaseProcessCodeType> processCodeTypeClass) {
        ConfigUtil.processCodeTypeClass = processCodeTypeClass;
    }
}
